<template>
    <div class="container">
        <div class="title">
            <img src="@/assets/imgs/sys/wechat-logo.png" alt="" />
            <span>微信支付 </span>
        </div>
        <div class="tip">
            <img class="tip_icon" src="@/assets/imgs/sys/wx-pay-tip.png" alt="" />
            <span class="tip_span">请确保微信支付与小程序APPID已经绑定！</span>
            <span class="tip_link top" @click="showRelatedHandler(1)">
                <el-icon><WarningFilled /></el-icon>
                如何绑定？
            </span>
        </div>
        <div class="list">
            <el-form
                :rules="rules"
                :disabled="false"
                ref="formRef"
                label-position="right"
                :model="form"
                label-width="auto">
                <el-form-item label="微信支付商户号" prop="merId">
                    <el-input class="input" v-model="form.merId" />
                    <span class="tip_link" @click="showRelatedHandler(2)">
                        <el-icon><WarningFilled /></el-icon>
                        如何查看微信支付商户号？
                    </span>
                </el-form-item>
                <el-form-item label="证书序列号" prop="serial">
                    <el-input class="input" v-model="form.serial" />
                    <span class="tip_link" @click="showRelatedHandler(3)">
                        <el-icon><WarningFilled /></el-icon>
                        如何查找证书序列号？
                    </span>
                </el-form-item>
                <el-form-item label="APIV3秘钥" prop="paySign">
                    <el-input class="input" v-model="form.paySign" />
                    <span class="tip_link" @click="showRelatedHandler(4)">
                        <el-icon><WarningFilled /></el-icon>
                        如何查找APIV3秘钥？
                    </span>
                </el-form-item>
                <el-form-item label="API证书" prop="cerPath" :error="uploadErrMsg.cerPath">
                    <template #label>
                        <div class="form_label">
                            <div><span class="star">* </span>API证书</div>
                            <div>(apiclient_cert.pem)</div>
                        </div>
                    </template>
                    <FileUpload
                        :merId="form.merId"
                        @clear="fileClear($event, 'cer')"
                        :files="buildFormFile('cer')"
                        @fileStateChange="fileChangeHandler($event, 'cer')">
                    </FileUpload>
                    <!-- 336 = 412 - 88 + 12 -->
                    <span
                        class="tip_link"
                        :style="{ 'margin-left': form.cerPath ? '12px' : '336px', 'align-self': 'flex-start' }"
                        @click="openWeiXinUrl">
                        <el-icon><WarningFilled /></el-icon>
                        如何查找API证书和API私钥
                    </span>
                </el-form-item>
                <el-form-item label="API私钥" prop="pfxPath" :error="uploadErrMsg.cerPath">
                    <template #label>
                        <div class="form_label">
                            <div><span class="star">* </span>API私钥</div>
                            <div>(apiclient_key.pem)</div>
                        </div>
                    </template>
                    <FileUpload
                        :merId="form.merId"
                        :files="buildFormFile('pfx')"
                        @clear="fileClear($event, 'pfx')"
                        @fileStateChange="fileChangeHandler($event, 'pfx')"></FileUpload>
                </el-form-item>
            </el-form>
            <div v-auth="'payMp:edit'" class="bottom">
                <el-button type="primary" size="large" @click="submitHandler">保 存</el-button>
            </div>
        </div>
        <ZwPayHelper ref="helperRef" />
    </div>
</template>
<script setup>
import { ref, reactive, onMounted, inject, computed } from 'vue';
import request from '@/request';
import { ElMessage } from 'element-plus';
import storage from '@/commons/storage';
import FileUpload from './upload.vue';
const paymentId = ref('');
const formRef = ref();
const form = reactive({
    // 商户号
    merId: '',
    // 证书序列号
    serial: '',
    // api密钥
    paySign: '',
    // api密钥密文
    paySignMosaic: '',
    cerPath: '',
    pfxPath: ''
});

// 自定义表单校验
const validateFields = ({ field }, value, callback) => {
    switch (field) {
        case 'cerPath':
            if (!value) {
                callback(new Error('请上传证书文件'));
            } else {
                callback();
            }
            break;
        case 'pfxPath':
            if (!value) {
                callback(new Error('请上传私钥文件'));
            } else {
                callback();
            }
            break;
        default:
            break;
    }
};
/**
 * 表单验证
 */
const rules = reactive({
    merId: [{ required: true, message: '请输入商户号', trigger: 'blur' }],
    serial: [{ required: true, message: '请输入证书序列号', trigger: 'blur' }],
    paySign: [{ required: true, message: '请输入API密钥', trigger: 'blur' }],
    cerPath: [{ validator: validateFields, trigger: 'blur' }],
    pfxPath: [{ validator: validateFields, trigger: 'blur' }]
});

const uploadErrMsg = reactive({
    cerPath: '',
    pfxPath: ''
});

// 文件回显
const buildFormFile = prop => {
    let arr = [];
    if (form[prop + 'Path']) {
        arr.push({
            name: form[prop + 'Name'] || form[prop + 'Path']?.split('/').pop(),
            url: form[prop + 'Path']
        });
    }
    return arr;
};

// 文件变更时
const fileChangeHandler = ({ fileUrl, fileName, msg }, prop) => {
    if (fileUrl !== undefined) {
        form[prop + 'Path'] = fileUrl || '';
        !msg && formRef.value.validateField(prop + 'Path');
    }
    if (fileName !== undefined) {
        form[prop + 'Name'] = fileName || '';
    }
    uploadErrMsg[prop] = msg || '';
};

/**
 * 提交
 */
const submitHandler = () => {
    formRef.value.validate(async valid => {
        if (valid) {
            baofuConfirmHandler(form);
        }
    });
};

// 更新或者保存
const baofuConfirmHandler = async form => {
    let para = {
        tenantId: storage.get('ZW-TENANT-ID'),
        serial: form.serial,
        paySign: form.paySign,
        merId: form.merId,
        terId: form.merId,
        cerPath: form.cerPath,
        privateKeyName: form.cerName,
        pfxPath: form.pfxPath,
        publicKeyName: form.pfxName,
        version: form.version,
        payChannel: 'WECHAT',
        subMerId: '二级商户'
    };
    let requestName = '';
    if (paymentId.value) {
        para = Object.assign(para, { id: paymentId.value });
        requestName = 'paymentUpdate';
    } else {
        requestName = 'paymentSave';
    }
    await request(requestName, para);
    ElMessage({
        type: 'success',
        message: '设置成功!'
    });
    init();
};

// 查paymentId
const init = async () => {
    const { data } = await request('paymentChannelList', {
        tenantId: storage.get('ZW-TENANT-ID'),
        payChannel: 'WECHAT'
    });
    if (data.list && data.list.some(item => item.channelCode === 'WECHAT' && item.paymentId > 0)) {
        paymentId.value = data.list.find(item => item.channelCode === 'WECHAT' && item.paymentId > 0).paymentId;
        initData();
    }
};

// initData
const initData = async () => {
    const { data } = await request('paymentInfo', {
        paymentId: paymentId.value
    });
    form.merId = data.merId;
    form.paySign = data.paySign;
    form.paySignMosaic = data.paySignMosaic;
    form.cerPath = data.tenantConfig?.privateKeyPath;
    form.pfxPath = data.tenantConfig?.certificatePath;
    form.serial = data.tenantConfig?.serial;
    form.cerName = data.private_key_name;
    form.pfxName = data.public_key_name;
    form.version = data.version;
};

// 删除文件
const fileClear = (event, prop) => {
    form[prop + 'Path'] = '';
    form[prop + 'Name'] = '';
};

const helperRef = ref(null);
const showRelatedHandler = val => {
    helperRef.value.onOpen(val);
};

const openWeiXinUrl = () => {
    window.open('https://kf.qq.com/faq/161222NneAJf161222U7fARv.html');
};

//初始化
onMounted(async () => {
    init();
});
</script>
<style lang="scss" src="./style.scss" scoped></style>
